/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


/* <![CDATA[ */
// Number of tweets to show for each column

var MAX_RESULTS = 0;
var searchBoxStatus = 1;
var screenWidth = screen.availWidth;
var tools_open = false;
var mode = "";
var tool = "";

function twitter_search() {
    //var consola = document.getElementById("consola");
    MAX_RESULTS = 10;//document.getElementById("num_results").value;
    var url = 'http://search.twitter.com/search.json?callback=?';
    // Iterating over the different search columns
    $('.twitterSearch').each(function() {
        var container = $(this);
        // Search terms are specified in the 'title' attribute
        var search =  "nike";//document.getElementById("query_search").value;
        //        var consola = document.getElementById("consola");
        //        consola.value = search;

/*        if (container.children().length)
        {
            container.children().each(function() {
                $(this).slideUp();
            });
        }*/

        container.empty();
        $('.twitterSearch').prepend('<div id="loadingdiv"><div class="loadingText"></div><div class="loading" ></div></div>');

        //consola.value = document.getElementById("num_results").value + " | " + document.getElementById("lang").value;

        if (search) {
            // Showing column title
            //            if (container.siblings('h1').length == 0) {
            //                container.parent().prepend('<h1>' + search + '</h1>');
            //            }
            //            else $("h1").html(search);
            // Request the results
            $.getJSON(url, {
                'q': search,
                'lang' : 'es',//document.getElementById("lang").value,
                'rpp' : MAX_RESULTS
            }, function(data) {
                // Processing those results, if any
                if (data.results.length) {
                    for (i in data.results.reverse()) {
                        var r = data.results[i];
                        // Creating the result container
                        var div = $('<div id="' + r.id + '"></div>');
                        var twitt = $('<div style="float:left"></div>');
                        twitt.addClass("twitt");
                        // Don't show this element now
                        div.hide();
                        //                        twitt.hide();
                        // Adding some styles through .twitter_result
                        div.addClass('twitter_result');
                        // Adding user's image
                        twitt.append('<img id="img' + r.id + '" src="' + r.profile_image_url + '" alt="' + r.from_user + '" />');
                        // Adding username
                        twitt.append('<a id="a' + r.id + '" href="http://twitter.com/' + r.from_user + '">' + r.from_user + '</a>');
                        // Adding tweet
                        twitt.append('<span id="text' + r.id + '">' + r.text + '</span>');
                        div.append(twitt);
                        //                        twitt.slideDown('fast');
                        // Adding icons
                        var controls = $('<div><img class="positive" src="img/dialog-ok.png" onclick="evaluated(1,' + r.id + ')" /><img class="negative" src="img/dialog-no.png" onclick="evaluated(0,' + r.id + ')" /></div>');
                        controls.addClass("controls");
                        div.append(controls);
                        // Adding corners
                        div.corner();
                        // Adding this result to the main container
                        container.prepend(div);
                        // Hidding loading
                        $("#loadingdiv").hide();
                        // Effect
                        div.slideDown('slow');
                    }
                    div.parent().prepend('<h1>' + search + '</h1>');
                //                    div.parent().prepend('<div class="error"></div>');


                //$(".twitterSearch").removeClass("container");
                }
            });
        }
    });
};


function show_tweets() {
    $(".twitterSearch").empty();
    $(".twitterSearch").load('jqGrid/grid.php');
}

/*function enviar(){

    if()
    alert("Has pulsado Intro");
}*/

function searchSubmitClick()
{
    if(event.keyCode == 13) $("#search_submit").click();
//    alert(event.keyCode);
}

function evaluated(polarity,id)
{
    $("#" + id).fadeOut(1000);
    $("#message").addClass("exito");
    //    $(".exito").removeClass("error");
    $(".exito").corner();
    $(".exito").empty();
    $(".exito").append('Guardando información...');
    var deshacer = '<div class="deshacer"><span style="float:left">Deshacer</span></div>'
    $(".exito").append(deshacer);
    $(".deshacer").corner();
    $(".exito").fadeIn("slow");
    $timeOut = setTimeout(function(){
        $(".exito").fadeOut(1000);
        $(".exito").load("nuevo.php", {
            id: id,
            userName: $("#a" + id).text(),
            imageURL: $("#img" + id).attr("src"),
            text: $("#text" + id).text(),
            polarity: polarity,
            submit: "Enviar"
        });
        $("#message").removeClass("exito");
    }, 5000);
    $(".deshacer").click(function(e) {
        e.preventDefault();
        clearTimeout($timeOut);
        $("#message").addClass("error");
        $(".error").removeClass("exito");
        //        $(".deshacer").hide();
        $(".error").empty();
        $(".error").prepend("Operacion cancelada");
        setTimeout(function(){
            $(".error ").fadeOut(1000);
        }, 2000);
        $("#message").removeClass("error");
        $("#" + id).fadeIn(1000);
    });

}


function show_tools() {
    var tools = $('<div></div>');
    var tools_content = $('<div></div>');
    var tools_bar = $('<div></div>');
    tools.addClass("tools");
    tools_content.addClass("tools_content");
    tools_bar.addClass("tools_bar");
    //    tools_bar.attr('title', 'Selecciona el modo')
    tools_content.append("<h1>TOOLS</h1>");
    tools_content.append('<div id="twitter_button" class="tool" title="Twitter"><img src="img/TwitterIcon.png" style="width:64px;height:64px;" /></div>');
    tools_content.append('<div id="fotolog_button" class="tool" title="Fotolog"> <img src="img/fotolog-icon2.png" style="width:64px;height:64px;" /></div>');
    tools_bar.append('<img src="img/tools/tools3.png"/>');
    tools.append(tools_content);
    tools.append(tools_bar);
    tools.append("<div class='tooltip'><h1>TOOLS</h1></div>");
    $("body").prepend(tools);
    $(".tools_bar").click(function() {
        var margin = $('.tools').css("margin-left").replace("px","");
        if(margin.charAt(0) == '-'){
            $(".tools").animate({
                'margin-left': "0px"
            },500);
            tools_open = true;
        }
        else {
            var tools_content_width = $('.tools_content').css("width");
            $(".tools").animate({
                'margin-left': "-" + tools_content_width
            }, 500);
            tools_open = false;
        }
    });
    $(".tools").css('margin-left', '-' + $(".tools_content").width() + "px");
    $("#twitter_button").click(function () {
        $("#work_div").addClass("twitterSearch");
        $(".tools_bar img").attr("src",$("#twitter_button img").attr("src"));
        show_twitter();
        $(".tools_bar").click();
        mode = "twitter";
        tool = "";
    });

    $("#fotolog_button").click(function() {
        $("#work_div").addClass("twitterSearch");
        $('.twitterSearch').prepend('<div id="loadingdiv"><div class="loadingText"></div><div class="loading" ></div></div>');
        $(".tools_bar img").attr("src",$("#fotolog_button img").attr("src"));
        $(".tools_bar").click();
        $(".exito").load("status.php",{
            mode : mode,
            tool : tool
        });
        mode = "fotolog";
        tool = "";
    });

    $("body").prepend('<div id="message"></div>');
    $("#message").addClass("exito");
//    alert("mode:" + mode + "\ntool:" + tool);
    if (mode == "twitter") {$("#twitter_button").click();}
    else if (mode == "fotolog") {$("#fotolog_button").click();}
//    $("#message").fadeIn('2000');

/*    var tools_panel = $('<div></div>');
    tools_panel.addClass("tools_panel");
    tools_panel.append('<div id="search" title="Busqueda en twitter" class="trigger"><img src="img/tools/Search-icon-big.gif" style="width:64px;height: 64px" /></div>');
    tools_panel.append('<div class="tooltip"><span>Search</span></div>');
    $("body").prepend('<a class="trigger" title="Herramientas" href="#"></a>');
    $("body").prepend(tools_panel);
    $(".tool").tooltip({effect: 'slide',position: 'center right',opacity:0.7});
    $("[title]").tooltip({effect: 'slide',position: 'center left',opacity:0.7});
    $(".tools_bar").tooltip({effect: 'slide',position: 'center right',opacity:0.7});*/

//    alert(screenWidth - $(".tools_bar").width() + "px");
}

function show_twitter() {
    var tools_panel = $('<div></div>');
    tools_panel.addClass("tools_panel");
    tools_panel.append('<div id="search" title="Busqueda en twitter" class="tool"><img src="img/tools/Search-icon-big.gif" style="width:64px;height: 64px" /></div>');
    tools_panel.append('<div id="show" title="Mostrar tweets guardados" class="tool"><img src="img/tools/Search-icon-big.gif" style="width:64px;height: 64px" /></div>');
    $("body").prepend('<a class="trigger" title="Herramientas" href="#"></a>');
    $("body").prepend(tools_panel);
    $(".trigger").click(function(){
        $(".tools_panel").toggle("fast");
        $(this).toggleClass("active");
        return false;
    });
    $("#search").click(function () {
        twitter_search();
        tool = "search";
        $(".trigger").click();
    });

    $("#show").click(function () {
        show_tweets();
        tool = "show";
        $(".trigger").click();
    });

    $("[title]").tooltip({
        effect: 'slide',
        position: 'center left',
        opacity:0.7
    });

    if (tool != "")
        {
            if (tool == "search"){$("#search").click();}
            if (tool == "show"){$("#show").click();}
        }

}


$(document).ready(function() {
    $(".pageContent").css('width',screenWidth - $(".tools_bar").width() + "px");


    $("#toppanel").mouseup(function() {
        return false
    });

    $(document).mouseup(function(e) {
        if($(e.target).parent("#toppanel").length==0 && $("#panel").css("display") != "none") {
            $("#close").click();
        }
        if(($(e.target).parent(".tools_bar").length==0) && tools_open) {
            $(".tools_bar").click();
        }
    });
    $(".tool").tooltip({
        effect: 'slide',
        position: 'center right',
        opacity:0.7
    });
    $(".tools_bar").tooltip({
        effect: 'slide',
        position: 'center right',
        opacity:0.7
    });



});

function addData(name,value,id,type) {
    var input = '<div class="input"><label class="grey" for="' + id + '">' + name + ':</label>';
    input = input + '<input class="inputround" type="' + type + '" name="' + id + '" id="' + id + '" value="' + value + '" size="23" disabled/></div>';
      return input;
};

function showUserData(nbyap,usr,email,dni,num,tlfn) {
    $("#work_div").empty();
    var container = $('<form id="data" action="" method="post">');
    container.addClass("container");
    container.append(addData("Nombre y Apellidos",nbyap,"nbyap"));
    container.append(addData("Nombre de usuario",usr,"usr"));
    container.append(addData("Email",email,"email"));
    container.append(addData("DNI",dni,"dni"));
    container.append(addData("Tel&eacute;fono",tlfn,"tlfn"));
    container.append(addData("N&uacute;mero en el equipo",num,"num"));
    container.append('<div class="input"><input id="editar" type="button" name="Editar" value="Editar"/></div>');
    $("#work_div").append(container);
    $("#close").click();
    $("#editar").click(function() {
        $("#data input").each(function(i,el) {
            $(el).attr("disabled", "");
            $(el).css("color","black");
            //alert($(el).val());
        });
    });
};


function validator() {
	$.validator.addMethod("dni", function(value) {
		return value.match(/^\d{1,8}[A-Z]{1}$/);
	}, 'Algo fue mal con tu DNI. Escríbe 8 CIFRAS poniendo ceros al principio si es necesario y una letra MAY&Uacute;SCULA al final');

        var validator = $("#rform").validate({
        rules: {
            username: {
                required: true,
                minlength: 2,
                remote: "users.php"
            },
            password: {
                required: true,
                minlength: 5
            },
            rpassword: {
                required: true,
                minlength: 5,
                equalTo: "#password"
            },
            email: {
                required: true,
                email: true,
                remote: "emails.php"
            },
            nbyap: "required",
            dni: "dni",
            tlfn: "tlfn",
            num: "required"
        },
        messages: {
            username: {
                required: "Introduce tu nombre de usuario",
                minlength: jQuery.format("Enter at least {0} characters"),
                remote: jQuery.format("{0} is already in use")
            },
            password: {
                required: "Provide a password",
                rangelength: jQuery.format("Enter at least {0} characters")
            },
            password_confirm: {
                required: "Repeat your password",
                minlength: jQuery.format("Enter at least {0} characters"),
                equalTo: "Enter the same password as above"
            },
            email: {
                required: "Please enter a valid email address",
                minlength: "Please enter a valid email address",
                remote: jQuery.format("{0} is already in use")
            },
            dateformat: "Choose your preferred dateformat",
            terms: " "
        },
        // the errorPlacement has to take the table layout into account
        errorPlacement: function(error, element) {
            if ( element.is(":radio") )
                error.appendTo( element.parent().next().next() );
            else if ( element.is(":checkbox") )
                error.appendTo ( element.next() );
            else
                error.appendTo( element.parent().next() );
        },
        // specifying a submitHandler prevents the default submit, good for the demo
        submitHandler: function() {
            alert("submitted!");
        },
        // set this class to error-labels to indicate valid fields
        success: function(label) {
            // set &nbsp; as text for IE
            label.html("&nbsp;").addClass("checked");
        }
    });
}